package com.xinxin.intelligenceexam.studyMenu.searchView;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.Toast;

import com.xinxin.intelligenceexam.R;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SearchViewActivity extends AppCompatActivity {

    @BindView(R.id.toolbar_search_view)
    Toolbar mToolbarSearchView;
    @BindView(R.id.activity_search_view)
    RelativeLayout mActivitySearchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_view);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbarSearchView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        Resources resources = getResources();
        final String [] testStrings = resources.getStringArray(R.array.test_search_view_array);
        getMenuInflater().inflate(R.menu.menu_search_view, menu);
        final MenuItem item = menu.findItem(R.id.search_view);
        final SearchView searchView = (SearchView) item.getActionView();
        //实现搜索历史
        int completeTextId = searchView.getResources().getIdentifier("android:id/search_src_text", null, null);
        AutoCompleteTextView completeText = (AutoCompleteTextView) searchView
                .findViewById(completeTextId) ;
        completeText.setAdapter(new ArrayAdapter<>(this,R.layout.list_item,R.id.text,testStrings));
        completeText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                searchView.setQuery(testStrings[position],true);
            }
        });
        completeText.setThreshold(0);//设置打多少字符给出提示

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(SearchViewActivity.this, query, Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }
}

